package action;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.hibernate.Session;

import sessionfactory.HibernateSessionFactory;
import classes.Ventes;

public class XmlProduitAction extends Action
{
	public ActionForward execute(ActionMapping 		mapping, 
			ActionForm 			form, 
			HttpServletRequest 	request, 
			HttpServletResponse response)
	
	throws IOException, ServletException 
	{
		ActionForward forward = null;
		
		Session session = HibernateSessionFactory.getSessionFactory().openSession();
		String idProduit = request.getParameter("id");
		List<Ventes> l = session.createQuery("FROM Ventes WHERE idProduit = '" + idProduit + "' ORDER BY time").list();
		List<Ventes> l2 = new ArrayList<Ventes>();

		String Xml;
		Integer j = 0;
		Date date = new Date ();
		SimpleDateFormat svf = new SimpleDateFormat ("dd/MM HH:mm:ss");
		Float maille = Float.valueOf(0);
		
		for (Ventes i:l)
		{
			if (date.getTime() != i.getTime())
			{
				Ventes tmp = new Ventes();
				tmp.setTime(i.getTime());
				tmp.setPrixHt((int)(maille * 100));

				l2.add(tmp);
				
				maille = Float.valueOf(0);
				date.setTime(i.getTime());
			}
			else
			{
					maille += i.getPrixHt();
			}
		}
		
		
		Xml = "<chart>\n";
		Xml += "       <xaxis>\n";
		for (Ventes i:l2)
		{
			date.setTime((i.getTime() / 100) * 100);
			Xml += "	       <value xid=\"" + j++ +  "\">" + svf.format(date) + "</value>\n";
		}
		Xml += "       </xaxis>\n";
		

		Xml += "		<graphs>\n";

		j =0;
		Xml += "       <graph gid=\"1\">\n";
		for (Ventes i:l2)
		{
			Xml += "	       <value xid=\"" + j++ +  "\">" + (i.getPrixHt() / 100) + "</value>\n";
		}
		Xml += "       </graph>\n";


		Xml += "		</graphs>\n";
		Xml += "</chart>\n";
        request.setAttribute("xml_stream", Xml);

        return mapping.findForward("Success");
	}
}

